package com.liuke.study.thread;

/**
 * TODO
 *
 * @author wangjwy
 * @date 2019/9/19 10:43
 * @since 1.0.0
 */
public class TestSynchronized {

	public static void main(String[] args) {
		TestA testA = new TestA();
		for (int i = 0; i < 1; i++) {
			new Thread(new MyThread(testA), "Thread" + i).start();
		}

		for (int i = 0; i < 1; i++) {
			new Thread(new MyThread2(testA), "Thread" + i).start();
		}

		// for (int i = 0; i < 3; i++) {
		// 	new Thread(new MyThread3(null), "Thread" + i).start();
		// 	new Thread(new MyThread2(testA), "Thread" + i*2).start();
		// }
		// new Thread(new MyThread(new TestA()), "Thread" + "LAST").start();
	}

}

class MyThread3 implements Runnable{

	private TestA testA;

	public MyThread3(TestA testA) {
		this.testA = testA;
	}

	@Override
	public void run() {
		try {
			TestA.testStatic();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class MyThread2 implements Runnable{

	private TestA testA;

	public MyThread2(TestA testA) {
		this.testA = testA;
	}

	@Override
	public void run() {
		try {
			testA.testCodeBlock2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class MyThread implements Runnable{

	private TestA testA;

	public MyThread(TestA testA) {
		this.testA = testA;
	}

	@Override
	public void run() {
		try {
			testA.testCodeBlock();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


class TestA {

	public void testCodeBlock() throws Exception {
		System.out.println(Thread.currentThread().getName() + "----start testCodeBlock");
		synchronized (Object.class){
			System.out.println(Thread.currentThread().getName() + "----synchronized start");
			Thread.sleep(5000);
			System.out.println(Thread.currentThread().getName() + "----synchronized end");
		}
		System.out.println(Thread.currentThread().getName() + "----end testCodeBlock");
	}

	public void testCodeBlock2() throws Exception {
		System.out.println(Thread.currentThread().getName() + "----2start testCodeBlock");
		synchronized (this){
			System.out.println(Thread.currentThread().getName() + "----2synchronized start");
			Thread.sleep(5000);
			System.out.println(Thread.currentThread().getName() + "----2synchronized end");
		}
		System.out.println(Thread.currentThread().getName() + "----2end testCodeBlock");
	}


	public synchronized static void testStatic() throws Exception {
		System.out.println(Thread.currentThread().getName() + "----3start testStatic");
		Thread.sleep(5000);
		System.out.println(Thread.currentThread().getName() + "----3end testStatic");
	}

}
